/**
 * Copyright (c) 2020 kedacom
 * OpenATC is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 * http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 **/
<template>
  <div class="openatc-operation common-comp-chart" ref="crossFlowChart">
    <div style="float:left;margin-top: 15px;margin-left: 20px;">
      <div class="common-table-title">{{$t('openatc.operation.operationfrequencyanalysis')}}</div>
    </div>
    <div class="filter-container" id="queryingCompFilters" style="margin-right:20px;">
        <div class="filter">
            <span class="header-span">{{$t('openatc.common.orgnizations') }}:</span>
            <el-select style="width: 120px;" @clear="getTree()" v-model="formId" clearable ref="selectTree">
            <el-option
            :key="form.id"
            :value="form.id"
            :label="form.label"
            hidden
            >
            </el-option>
            <el-tree
            :data="datalist"
            default-expand-all
            :props="defaultProps"
            @node-click="handleClickNode"
            node-key="id">
            </el-tree>
            </el-select>
        </div>
        <div class="filter">
            <span class="header-span">{{$t('openatc.operation.roadname') }}：</span>
            <el-select
                v-model="road"
                clearable
            >
                <el-option
                v-for="(option, index) in roadList"
                :key="index"
                :label="option.label"
                :value="option.value"
                >
                </el-option>
            </el-select>
        </div>
        <div class="filter">
            <span class="header-span">{{$t('openatc.operation.type') }}：</span>
            <el-select
            v-model="controlTypes"
            clearable
            filterable>
            <el-option
                v-for="(item, index) in controlType"
                :key="index"
                :label="item.label"
                :value="item.value"
            >
            </el-option>
            </el-select>
        </div>
        <div class="filter timepicker">
          <span class="header-span">{{$t('openatc.operation.time') }}：</span>
          <template>
            <el-date-picker
                popper-class="common-date-popper"
                v-model="timeValue"
                align="center"
                type="daterange"
                :range-separator="$t('openatc.usermanager.to')"
                :start-placeholder="$t('openatc.usermanager.starttime')"
                :end-placeholder="$t('openatc.usermanager.endtime')">
            </el-date-picker>
          </template>
        </div>
        <div class="filter">
            <span class="header-span">{{$t('openatc.operation.interval') }}：</span>
            <el-select
            v-model="interval"
            clearable
            filterable>
            <el-option
                v-for="(item, index) in intervalList"
                :key="index"
                :label="item.label"
                :value="item.value"
            >
            </el-option>
            </el-select>
        </div>
        <div class="filter filters">
            <el-button type="primary" class="add-btn" icon="el-icon-search" @click="handleFilters"></el-button>
        </div>
        <el-dropdown trigger="click" @command="handleCommand">
            <el-button type="primary">
                {{$t('openatc.operation.export')}}<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown" style="width: 110px">
                <el-dropdown-item command="exportCSV" style="line-height: 32px;text-align: center;">
                    csv
                </el-dropdown-item>
                <el-dropdown-item command="exportHTML" style="line-height: 32px;text-align: center;">
                    html
                </el-dropdown-item>
                <el-dropdown-item command="exportPDF" style="line-height: 32px;text-align: center;">
                    pdf
                </el-dropdown-item>
            </el-dropdown-menu>
        </el-dropdown>
    </div>
    <!-- <div class="tittle">{{$t('openatc.operation.operationfrequencyanalysis')}}</div> -->
    <!-- <CompFilters showCycle id="queryingCompFilters" @handlefilters="handleAddCompareLine" @handleExportPDF="handleExportPDF" @handleExportHTML="handleExportHTML" @handleExportCSV="handleExportCSV" /> -->
    <!-- <CompFiltersTags :filterTags="filterTags" @handleCloseTag="handleCloseTag" /> -->
    <div class="analysis-charts">
        <div class="charts"  id="crossflow"></div>
    </div>
  </div>
</template>

<script>
import * as echart from 'echarts'
// import moment from 'moment'
// import CompFilters from './compFilters.vue'
import { getTheme } from '../../utils/auth'
import { GetOrganizationList } from '../../api/organization'
import { elTreeModel } from '../../model/tree/eltreemodel'
import { getDeviceRange, getOperationData } from '../../api/device'
import moment from 'moment'
// import { GetDevicesByOrgCode } from '../../api/relate'
import { downloadPDF } from '../../utils/exportHtmlToPdf.js'
import { ExportEchartsHtml } from '../../utils/exportChartsToHtml.js'
import { ExportHistoricalStatistics } from '../../utils/exportExcel.js'
// import { TrafficOperStatisticsApi } from '../../../api/trafficOperStatistics.js'
import { getMessageByCode } from '../../utils/responseMessage'
export default {
  components: {
    // CompFilters
  },
  data () {
    return {
      defaultProps: {
        value: 'id',
        label: 'label',
        children: 'children'
      },
      timeValue: this.getDefaultDate(),
      controlTypes: '201',
      controlType: [
        {
          label: this.$t('openatc.dutyroute.controlType0'),
          value: '0'
        },
        {
          label: this.$t('openatc.dutyroute.controlType1'),
          value: '1'
        },
        {
          label: this.$t('openatc.dutyroute.controlType2'),
          value: '2'
        },
        {
          label: this.$t('openatc.dutyroute.controlType3'),
          value: '3'
        },
        {
          label: this.$t('openatc.dutyroute.controlType4'),
          value: '4'
        },
        {
          label: this.$t('openatc.dutyroute.controlType5'),
          value: '5'
        },
        {
          label: this.$t('openatc.dutyroute.controlType6'),
          value: '6'
        },
        {
          label: this.$t('openatc.dutyroute.controlType7'),
          value: '7'
        },
        {
          label: this.$t('openatc.dutyroute.controlType8'),
          value: '8'
        },
        {
          label: this.$t('openatc.dutyroute.controlType9'),
          value: '9'
        },
        {
          label: this.$t('openatc.dutyroute.controlType10'),
          value: '10'
        },
        {
          label: this.$t('openatc.dutyroute.controlType11'),
          value: '11'
        },
        {
          label: this.$t('openatc.dutyroute.controlType12'),
          value: '12'
        },
        {
          label: this.$t('openatc.dutyroute.controlType13'),
          value: '13'
        },
        {
          label: this.$t('openatc.dutyroute.controlType14'),
          value: '14'
        },
        {
          label: this.$t('openatc.dutyroute.controlType15'),
          value: '15'
        },
        {
          label: this.$t('openatc.dutyroute.controlType16'),
          value: '16'
        },
        {
          label: this.$t('openatc.dutyroute.controlType17'),
          value: '17'
        },
        // {
        //   label: this.$t('openatc.dutyroute.controlType18'),
        //   value: 18
        // },
        {
          label: this.$t('openatc.dutyroute.controlType19'),
          value: '19'
        },
        // {
        //   label: this.$t('openatc.dutyroute.controlType21'),
        //   value: 21
        // },
        {
          label: this.$t('openatc.dutyroute.controlType22'),
          value: '22'
        },
        {
          label: this.$t('openatc.dutyroute.controlType23'),
          value: '23'
        },
        {
          label: this.$t('openatc.dutyroute.controlType24'),
          value: '24'
        },
        {
          label: this.$t('openatc.dutyroute.controlType99'),
          value: '99'
        },
        {
          label: this.$t('openatc.dutyroute.controlType100'),
          value: '100'
        },
        {
          label: this.$t('openatc.dutyroute.controlType201'),
          value: '201'
        }
      ],
      intervalList: [
        {
          label: this.$t('openatc.operation.day'),
          value: 'day'
        },
        {
          label: this.$t('openatc.operation.hour'),
          value: 'hour'
        }
      ],
      interval: '',
      datalist: [],
      formId: '',
      form: {
        id: '',
        label: '',
        code: ''
      },
      road: '',
      roadList: [],
      loading: false,
      allLineData: [], // 当前所有曲线数据
      allCharts: [], // 折线图所需数据
      legends: [],
      csvData: new Map()
    }
  },
  created () {
    this.getList()
  },
  methods: {
    handleCommand (command) {
      switch (command) {
        case 'exportCSV': this.handleExportCSV()
          break
        case 'exportHTML': this.handleExportHTML()
          break
        case 'exportPDF': this.handleExportPDF()
          break
        default: console.log('no command!')
      }
    },
    getList () {
      // 查询所有
      GetOrganizationList().then(data => {
        if (data.data.code === '401') { // 判断用户是否在其他地方被踢出
          window.location.reload()
          return
        }
        if (data.data.success !== true) {
          this.$message.error(getMessageByCode(data.data.code, this.$i18n.locale))
          return
        }
        this.datalist = elTreeModel.CreateTreeByPath(data.data.data)
      })
    },
    getDeviceRanges (code) {
      this.roadList = []
      let reqData = {
        'pageNum': 1,
        'pageRow': 10000,
        'search': '',
        'type': '',
        'platform': '',
        'protocol': '',
        'state': '',
        'code': code,
        'control': -1,
        'mode': -1,
        'tags': ''
      }
      getDeviceRange(reqData).then(res => {
        if (!res.data.success) {
          this.$message.error(getMessageByCode(res.data.code, this.$i18n.locale))
          return
        }
        this.roadList = res.data.data.content.map(item => {
          return {
            label: item.name,
            value: item.agentid
          }
        })
      })
    },
    handleFilters () {
      if (this.formId === '') {
        this.$message({
          message: this.$t('openatc.operation.orgnizationsempty'),
          type: 'warning'
        })
        return
      }
      if (this.road === '') {
        this.$message({
          message: this.$t('openatc.operation.rodeempty'),
          type: 'warning'
        })
        return
      }
      if (this.controlTypes === '') {
        this.$message({
          message: this.$t('openatc.operation.typeempty'),
          type: 'warning'
        })
        return
      }
      if (this.timeValue === null) {
        this.$message({
          message: this.$t('openatc.operation.timeempty'),
          type: 'warning'
        })
        return
      }
      if (this.interval === '') {
        this.$message({
          message: this.$t('openatc.operation.intervalempty'),
          type: 'warning'
        })
        return
      }
      this.refreshChart()
    },
    getTree () {
    //   this.listQuery.pageNum = 1
      this.form.id = ''
      this.form.code = ''
      this.form.label = ''
      this.road = ''
      this.roadList = []
    //   this.getTableData()
    },
    // 节点点击事件
    handleClickNode (data) {
      this.formId = data.label
      this.form.id = data.id
      this.form.code = data.code
      this.form.label = data.label
      this.$refs.selectTree.blur()
      //   this.listQuery.pageNum = 1
      this.getDeviceRanges(data.code)
    //   this.getTableData()
    },
    getRouteFlow () {
      let reqData = {
        'code': this.formId,
        'agentid': this.road,
        'type': this.controlTypes,
        'intervalType': this.interval
      }
      if (this.timeValue !== null) {
        let startTime = moment(this.timeValue[0]).format('YYYY-MM-DD') + ' 00:00:00'
        let endTime = moment(this.timeValue[1]).format('YYYY-MM-DD') + ' 23:59:59'
        reqData.startTime = startTime
        reqData.endTime = endTime
      }
      return new Promise((resolve, reject) => {
        getOperationData(reqData).then((res) => {
        //   this.legends = []
          if (!res.data.success) {
            this.$message.error(getMessageByCode(res.data.code, this.$i18n.locale))
            return
          }
          let phaseStatic = res.data.data
          resolve(phaseStatic)
        })
      })
    },
    lockScreen () {
      this.loading = true
    },
    unlockScreen () {
      this.loading = false
    },
    getDefaultDate () {
      let end = new Date()
      let start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [moment(start).format('YYYY-MM-DD'), moment(end).format('YYYY-MM-DD')]
    },
    initChart () {
      this.crosssChart = echart.init(document.getElementById('crossflow'))
      const _this = this
      window.onresize = function () {
        _this.crosssChart.resize()
      }
    },
    refreshStrengthChart () {
      return this.getRouteFlow().then(data => {
        this.curAddcrosssData = JSON.parse(JSON.stringify(data))
        this.csvData.clear()
        this.csvData.set(data.agentid + this.$t('openatc.operation.count'), this.curAddcrosssData.data)
        this.allLineData = this.curAddcrosssData
        this.getStrSeries(this.allLineData)
        this.crosssChart.clear()
        this.renderStrengthChart()
      })
    },
    renderStrengthChart () {
      if (this.allCharts.length === 0) {
        this.crosssChart.clear()
        return
      }
      // 渲染
      let strOption = this.getStrOption()
      this.crosssChart.setOption(strOption, true)
    },
    // 渲染
    getStrOption () {
      let strOption = {
        tooltip: {
          trigger: 'axis'
        },
        title: {
          text: `${this.$t('openatc.operation.total') + this.allCharts[0].total}`,
          x: 'center',
          textStyle: {
            color: getTheme() === 'light' ? '#666666' : '#B9BABF'
          }
        },
        legend: {
          bottom: 60,
          textStyle: {
            color: getTheme() === 'light' ? '#666666' : '#B9BABF'
          },
          data: this.allCharts.length > 0 ? [this.allCharts[0].name] : []
        },
        grid: {
          containLabel: true,
          height: '80%',
          width: '100%',
          right: '30',
          left: '30',
          bottom: '100'
        },
        toolbox: {
          right: '10%',
          top: '10%',
          feature: {
            saveAsImage: {
              name: this.$t('openatc.operation.operationfrequencyanalysis'),
              title: this.$t('openatc.operation.savepng')
            }
          }
        },
        xAxis: [
          {
            type: 'category',
            boundaryGap: true,
            axisLabel: {
              rotate: '8',
              margin: 20,
              align: 'center',
              textStyle: {
                color: getTheme() === 'light' ? '#666666' : '#B9BABF'
              }
            },
            axisTick: {
              show: true,
              length: 6,
              alignWithLabel: true,
              lineStyle: {
                color: getTheme() === 'light' ? '#D7DFE1' : '#30384D'
              }
            },
            axisLine: {
              lineStyle: {
                color: getTheme() === 'light' ? '#D7DFE1' : '#30384D'
              }
            },
            data: this.allCharts.length > 0 ? this.allCharts[0].time : []
          }
        ],
        yAxis: [
          {
            type: 'value',
            // name: this.allCharts.length > 0 ? this.allCharts[0].name : '',
            axisTick: {
              lineStyle: {
                color: getTheme() === 'light' ? '#D7DFE1' : '#30384D'
              }
            },
            axisLine: {
              lineStyle: {
                color: getTheme() === 'light' ? '#D7DFE1' : '#30384D'
              }
            },
            splitLine: {
              lineStyle: {
                color: getTheme() === 'light' ? '#DCDFE6' : '#30384d'
              }
            },
            splitArea: {
              show: true,
              areaStyle: {
                color: getTheme() === 'light' ? ['#fafafa', '#fff'] : ['#202940', '#1a2338']
              }
            },
            axisLabel: {
              textStyle: {
                color: getTheme() === 'light' ? '#666666' : '#B9BABF'
              }
            }
          }
        ],
        dataZoom: [
          {
            type: 'inside',
            start: 0,
            end: 100
          },
          {
            start: 0,
            end: 100
          }
        ],
        series: [...this.allCharts]
      }
      return strOption
    //   this.crosssChart.setOption(this.strOption, true)
    },
    getStrSeries (datas) {
      let seriesBar = {
        name: datas.agentid,
        type: 'bar',
        total: datas.total,
        // barMaxWidth: 10,
        time: datas.data.map(item => item.time),
        data: datas.data.map(item => item.count),
        connectNulls: true
      }
      this.allCharts = [seriesBar]
    },
    async refreshChart () {
      this.lockScreen()
      this.refreshStrengthChart()
      this.unlockScreen()
    },
    handleExportPDF () {
      // 导出PDF
      // 暂时让筛选项隐藏，因为html2canvas不支持css3样式
      let filterDiv = document.getElementById('queryingCompFilters')
      filterDiv.style.display = 'none'
      downloadPDF(this.$refs.crossFlowChart, this.$t('openatc.operation.operationfrequencyanalysis'))
      // 导出pdf后，再让筛选项显示
      filterDiv.style.display = 'block'
    },
    handleExportHTML () {
      let strOption = this.getStrOption()
      let echartsOptions = JSON.parse(JSON.stringify(strOption))
      echartsOptions.tooltip.extraCssText = 'min-height:200px;'
      let params = {
        echartsOptions,
        htmlname: this.$t('openatc.operation.operationfrequencyanalysis'),
        tmpTitle: this.$t('openatc.operation.operationfrequencyanalysis'),
        // filterTagsStr: this.getTagStr(),
        bgColor: getTheme() === 'light' ? '#F5F7FA' : '#191F34',
        tittleColor: getTheme() === 'light' ? '#303133' : '#fff',
        tagBgColor: getTheme() === 'light' ? '#ecf5ff' : '#233553',
        tagBorderColor: getTheme() === 'light' ? '#d9ecff' : '#264066'
      }
      ExportEchartsHtml(params)
    },
    handleExportCSV () {
      let exportdata = new Map()
      for (let [key, val] of this.csvData) {
        for (let data of val) {
          let time = data.time
          if (exportdata.has(time)) {
            let param = {
              key,
              value: (data.count || data.count === 0) ? (data.count || 0) : data.count
            }
            let mapdata = exportdata.get(time)
            mapdata.push(param)
            exportdata.set(time, mapdata)
          } else {
            let param = {
              key,
              value: (data.count || data.count === 0) ? (data.count || 0) : data.count
            }
            exportdata.set(time, [param])
          }
        }
      }
      let exportarr = []
      if (exportdata.size > 0) {
        for (let [key, val] of exportdata) {
          let exportfield = {
            '时间': key
          }
          for (let j = 0; j < val.length; j++) {
            let cur = val[j]
            exportfield[`数据${cur.key}`] = cur.value
          }
          exportarr.push(exportfield)
        }
        ExportHistoricalStatistics(exportarr, this.$t('openatc.operation.operationfrequencyanalysis'), [])
      }
    }

  },
  mounted () {
    this.initChart()
  }
}

</script>

<style>

</style>
